layui.use('layer', function () {
    const layer = layui.layer;
    $.fn.onAxiosSuccess = function (ret, onAxiosSuccess) {
        var data = typeof ret.data !== 'undefined' ? ret.data : null;
        var msg = typeof ret.msg !== 'undefined' ? ret.msg : '';
        if (typeof onAxiosSuccess === 'function') {
            var result = onAxiosSuccess.call(this, data, ret);
            if (result === false)
                return;
        }
        if (msg != '') {
            layer.msg(msg);
        }
    };
    $.fn.onAxiosError = function (ret, onAxiosError) {
        var data = typeof ret.data !== 'undefined' ? ret.data : null;
        var msg = typeof ret.msg !== 'undefined' && ret.msg != '' ? ret.msg : '';
        if (typeof onAxiosError === 'function') {
            var result = onAxiosError.call(this, data, ret);
            if (result === false) {
                return false;
            }
        }
        layer.msg(msg);
    };
    $.fn.onAxiosResponse = function (response) {
        try {
            response = typeof response === 'object' ? response : JSON.parse(response);
            if (!response.hasOwnProperty('data')) {
                var ret = {};
                let msg =response.message +' 系统提示:'+ response.response.data.message;
                $.extend(ret, {code: -1, msg: msg, data: null});
            } else {
                var ret = response.data;
            }
        } catch (e) {
            var ret = {code: -2, msg: e.message, data: null};
        }
        return ret;
    }

    $.fn.myaxios = function (options, success, error) {
        options = typeof options === 'string' ? {url: options} : options;
        let index;
        if (options.loading != undefined) {
            index = layer.load(options.loading || 0);
        }
        if (options.method == undefined) {
            options.method = 'POST';
        }
        axios(options).then(function (response) {
            index && layer.close(index);
            let ret = $.fn.onAxiosResponse(response);
            if (ret.code == 1) {
                $.fn.onAxiosSuccess(ret, success)
            } else {
                $.fn.onAxiosError(ret, error);
            }
        }).catch(function (response) {
            index && layer.close(index);
            let ret = $.fn.onAxiosResponse(response);
            $.fn.onAxiosError(ret, error);
        });
        return false;
    }
})


